/**
 * @file   xmega.c
 * @brief  Atmel Xmega initialization and control
 *
 * @date   2011/04/23
 * @author K.Akasaka
 *
 */

#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>

#include "core/include/types.h"

static BYTE systemClockMHz;

BOOL Init_processor(BYTE clkMHz)
{
    systemClockMHz = clkMHz;

	/* OSC setting */
	/*- XOCSCTRL <- FREQ Range=12Mhz - 16MHz, XOSCSEL=0.4-16MHz */
	OSC.XOSCCTRL = OSC_FRQRANGE_12TO16_gc | OSC_XOSCSEL_XTAL_16KCLK_gc ;

	/*- CTRL */
	OSC.CTRL |= OSC_RC32MEN_bm | OSC_XOSCEN_bm;

	/* wait for stable */
    while( (OSC.STATUS & OSC_RC32MRDY_bm) == 0 );
    while( (OSC.STATUS & OSC_XOSCRDY_bm)  == 0 );

	/*- PLLCTRL <- SRC = XOCS, PLLFAC = 8 */
	CPU_CCP = CCP_IOREG_gc; // magic word
	CLK.PSCTRL = CLK_PSBCDIV_1_2_gc;

	OSC.PLLCTRL = OSC_PLLSRC_XOSC_gc | 4;
	OSC.CTRL   |= OSC_PLLEN_bm;

	/* wait for stable */
	while( (OSC.STATUS & OSC_PLLRDY_bm)  == 0 );

	/* clock setting */
	CPU_CCP  = CCP_IOREG_gc; // magic word
	CLK.CTRL = CLK_SCLKSEL_PLL_gc; // CLOCK SOURCE = PLL


	/* EBI Setting */
	EBI.CS0.CTRLA = EBI_CS_ASIZE_16M_gc | EBI_CS_MODE_SRAM_gc;
	EBI.CS0.CTRLB = 6;
	EBI.CS0.BASEADDR = 0x000000;
	EBI.CTRL = EBI_SRMODE_ALE12_gc | EBI_IFMODE_3PORT_gc;

	PORTA.DIRSET = 0xFF;
	PORTB.DIRSET = 0x0A;
//	PORTC.DIRSET = 0x03;
//	PORTD.DIRSET = 0xFF;
//	PORTE.DIRSET = 0xFF;
//	PORTF.DIRSET = 0xFF;
	PORTH.DIRSET = 0xFF;
	PORTJ.DIRSET = 0x00;
	PORTK.DIRSET = 0xFF;

	return TRUE;
}


BYTE getSystemClockMHz(void)
{
    return systemClockMHz;
}
